package com.itheima.reggie.controller;

import com.aliyuncs.http.HttpRequest;
import com.aliyuncs.http.HttpResponse;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String path;
    @PostMapping("/upload")
    public R<String> upload( MultipartFile file) throws IOException {
        //获取目标的文件名
        String originalFilename = file.getOriginalFilename();
        //将目标文件名进行截取
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        String uuidFilename = UUID.randomUUID().toString() + substring;
        //创建磁盘目录
        File dr = new File(path);
        //判断目录是否创建
        if(!dr.exists()){
            dr.mkdirs();
        }
        //将文件写入到磁盘的目录之中
        file.transferTo(new File(path+uuidFilename));

        //返回
        return R.success(uuidFilename);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        FileInputStream filename = new FileInputStream(path+name);

        ServletOutputStream outputStream = response.getOutputStream();
         byte[] by=new byte[1024];
         int length;
         while ((length=filename.read(by))!=-1){
             outputStream.write(by,0,length);
         }

         //关闭流
        filename.close();
    }
}
